var express = require('express');
var router = express.Router();
var { conn, isError, dateFormat, isLogin } = require("../untils");
var { ObjectID } = require("mongodb");
var { series } = require("async");

router.get('/comments', function (req, res) {
    var session_username = req.session.username;
    var count = 0;   // 所有评论的条数 
    var totalPage = 0;  //  总页数 
    var pageSize = 5;  // 每页显示 5条
    var pageNo = parseInt(req.query['pageNo']) || 0;  // 当前的页码 
    var _id = ObjectID(req.query._id);
    var db_name = req.query.db_name;
    var news_info = null;
    conn((err, db) => {
        isError(err, res, db);
        if (db_name === "index") {
            news_info = db.collection("news_index_info");
        } else if (db_name === "television") {
            news_info = db.collection("news_television_info");
        } else if (db_name === "movie") {
            news_info = db.collection("news_movie_info");
        } else if (db_name === "star") {
            news_info = db.collection("news_star_info");
        } else if (db_name === "music") {
            news_info = db.collection("news_music_info");
        }
        var news_comments = db.collection("news_comments");
        series([
            (callback) => {
                news_info.find({ _id }, {}).toArray((err, result) => {
                    if (err) {
                        callback(err, null);
                    } else {
                        callback(null, result[0]);
                    }
                });
            },
            (callback) => {
                news_comments.find({ status: 1, news_id: _id }, {}).toArray((err, result) => {
                    if (err) {
                        callback(err, null)
                    } else {
                        count = result.length;
                        totalPage = Math.ceil(count / pageSize);
                        pageNo = pageNo >= totalPage ? totalPage : pageNo;
                        pageNo = pageNo <= 1 ? 1 : pageNo;
                        callback(null, true);
                    }
                })
            },
            (callback) => {
                news_comments.find({ status: 1, news_id: _id }, {}).sort({ insert_time: -1 }).skip((pageNo - 1) * pageSize).limit(pageSize).toArray((err, result) => {
                    if (err) {
                        callback(err, null);
                    } else {
                        callback(null, result);
                    }
                })
            }
        ], (err, result) => {
            isError(err, res, db);
            res.render('comments', { session_username, news_result: result[0], comments_result: result[2], db_name, _id, count, totalPage, pageNo });
            db.close();
        });
    });
});

router.get('/submit', function (req, res) {
    var session_username = req.session.username;
    var content = req.cookies.news_content;
    var db_name = req.query.db_name;
    var _id = req.query._id;
    var title = req.cookies.news_title;
    isLogin(session_username, res, () => {
        conn((err, db) => {
            isError(err, res, db);
            var news_comments = db.collection("news_comments");
            var insert_time = dateFormat(new Date(), "yyyy年mm月dd日 hh时SS分ss秒");
            var news_id = ObjectID(_id);
            news_comments.insert({ status: 1, news_id, content, username: session_username, title, insert_time }, (err, result) => {
                isError(err, res, db);
                res.cookie("news_content", "", { maxAge: 1 });
                res.cookie("news_title", "", { maxAge: 1 });
                res.redirect(`/comments/comments?db_name=${db_name}&_id=${_id}`);
                db.close();
            })
        });
    });
});

router.get('/my_comments', function (req, res) {
    var session_username = req.session.username;
    var count = 0;   // 所有评论的条数 
    var totalPage = 0;  //  总页数 
    var pageSize = 5;  // 每页显示 5条
    var pageNo = parseInt(req.query['pageNo']) || 0;  // 当前的页码 
    var search_key = req.cookies.search_key || "";
    var insert_time = parseInt(req.query['insert_time']) || -1;
    isLogin(session_username, res, () => {
        conn((err, db) => {
            isError(err, res, db);
            var news_comments = db.collection("news_comments");
            series([
                (callback) => {
                    news_comments.find({ title: new RegExp(search_key), status: 1, username: session_username }, {}).toArray((err, result) => {
                        if (err) {
                            callback(err, null)
                        } else {
                            count = result.length;
                            totalPage = Math.ceil(count / pageSize);
                            pageNo = pageNo >= totalPage ? totalPage : pageNo;
                            pageNo = pageNo <= 1 ? 1 : pageNo;
                            callback(null, true);
                        }
                    })
                },
                (callback) => {
                    news_comments.find({ title: new RegExp(search_key), status: 1, username: session_username }, {}).sort({ insert_time: insert_time }).skip((pageNo - 1) * pageSize).limit(pageSize).toArray((err, result) => {
                        if (err) {
                            callback(err, null);
                        } else {
                            callback(null, result);
                        }
                    })
                }
            ], (err, result) => {
                isError(err, res, db);
                res.render('my_comments', { session_username, comments_result: result[1], count, totalPage, pageNo });
                db.close();
            });
        });
    });
});

router.get('/remove', function (req, res) {
    var session_username = req.session.username;
    var remove_id = req.cookies.remove_id;
    var obj = {};
    obj.status = 1;
    obj.username = session_username;
    if (remove_id !== "-1") {
        obj._id = ObjectID(remove_id);
    }
    isLogin(session_username, res, () => {
        conn((err, db) => {
            isError(err, res, db);
            var news_comments = db.collection("news_comments");
            news_comments.updateMany(obj, { $set: { status: 0 } }, (err, result) => {
                isError(err, res, db);
                res.cookie("remove_id", "", { maxAge: 1 });
                res.redirect("my_comments");
                db.close();
            })
        });
    });
});

router.get('/update', function (req, res) {
    var session_username = req.session.username;
    var _id = ObjectID(req.cookies.update_id);
    var content = req.cookies.update_content;
    isLogin(session_username, res, () => {
        conn((err, db) => {
            isError(err, res, db);
            var news_comments = db.collection("news_comments");
            var insert_time = dateFormat(new Date(), "yyyy年mm月dd日 hh时SS分ss秒");
            news_comments.update({ status: 1, _id }, { $set: { content, insert_time } }, (err, result) => {
                isError(err, res, db);
                res.cookie("update_id", "", { maxAge: 1 });
                res.cookie("update_content", "", { maxAge: 1 });
                res.redirect("my_comments");
                db.close();
            });
        });
    })
});

var multiparty = require("multiparty");
var fs = require("fs");
// 上传图片
router.post("/uploadImg", (req, res) => {
    var form = new multiparty.Form();   // 实例化 
    // 编码
    form.encoding = "UTF-8";
    // 图片上传的临时存储路径 
    form.uploadDir = "./uploadtemp";
    // 图片的最大内存  
    form.maxFilesSize = 8 * 1024 * 1024   // 8M
    form.parse(req, (err, fields, files) => {
        if (err) {
            res.json({ err: err, msg: "上传图片失败" });
            throw err;
        }
        // fields  文件域 
        // files 文件 
        var uploadUrl = "/images/upload/";   // 文件的服务器路径 
        file = files['filedata']; // 当前图片对象 
        originalFilename = file[0].originalFilename  // 文件的初始化名称  // 1.jpg  

        tempath = file[0].path;  // 文件的临时路径  

        var timestamp = new Date().getTime();  // 时间戳 
        uploadUrl += timestamp + originalFilename;  //   /images/upload/8888881.jpg 
        newpath = "./public" + uploadUrl;

        // 通过文件流读取图片 
        var fileReadStream = fs.createReadStream(tempath);
        var fileWriteStream = fs.createWriteStream(newpath);

        fileReadStream.pipe(fileWriteStream);  // 读取文件  
        // 监听文件上传 
        fileWriteStream.on("close", () => {
            // 删除临时文件 
            fs.unlinkSync(tempath);
            res.json({ err: '', msg: uploadUrl })
        })

    })
})

module.exports = router;